<?
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Group
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

bx_import('BxDolTwigModuleDb');

/*
 * Groups module Data
 */
class BxGroupsDb extends BxDolTwigModuleDb {	

	/*
	 * Constructor.
	 */
	function BxGroupsDb(&$oConfig) {
        parent::BxDolTwigModuleDb($oConfig);
 
		$this->_oConfig = $oConfig;
 
		/********Sponsor ************/
        $this->_sTableSponsor = 'sponsor_main';
        $this->_sSponsorPrefix = 'bx_groups_sponsor';
        $this->_sTableSponsorMediaPrefix = 'sponsor_';

		/********Event ************/
        $this->_sTableEvent = 'event_main';
        $this->_sEventPrefix = 'bx_groups_event';
        $this->_sTableEventMediaPrefix = 'event_';
 
		/********Venue ************/
        $this->_sTableVenue = 'venue_main';
        $this->_sVenuePrefix = 'bx_groups_venue';
        $this->_sTableVenueMediaPrefix = 'venue_';

		/********News ************/
        $this->_sTableNews = 'news_main';
        $this->_sNewsPrefix = 'bx_groups_news';
        $this->_sTableNewsMediaPrefix = 'news_';



        $this->_sTableMain = 'main';
        $this->_sTableMediaPrefix = '';
        $this->_sFieldId = 'id';
        $this->_sFieldAuthorId = 'author_id';
        $this->_sFieldUri = 'uri';
        $this->_sFieldTitle = 'title';
        $this->_sFieldDescription = 'desc';
        $this->_sFieldTags = 'tags';
        $this->_sFieldThumb = 'thumb';
        $this->_sFieldStatus = 'status';
        $this->_sFieldFeatured = 'featured';
        $this->_sFieldCreated = 'created';
        $this->_sFieldJoinConfirmation = 'join_confirmation';
        $this->_sFieldFansCount = 'fans_count';
        $this->_sTableFans = 'fans';
        $this->_sTableAdmins = 'admins';
        $this->_sFieldAllowViewTo = 'allow_view_group_to';
	}

    function deleteEntryByIdAndOwner ($iId, $iOwner, $isAdmin) {
        if ($iRet = parent::deleteEntryByIdAndOwner ($iId, $iOwner, $isAdmin)) {
            $this->query ("DELETE FROM `" . $this->_sPrefix . "fans` WHERE `id_entry` = $iId");
            $this->query ("DELETE FROM `" . $this->_sPrefix . "admins` WHERE `id_entry` = $iId");
            $this->deleteEntryMediaAll ($iId, 'images');
            $this->deleteEntryMediaAll ($iId, 'videos');
            $this->deleteEntryMediaAll ($iId, 'sounds');
            $this->deleteEntryMediaAll ($iId, 'files');

             $this->query ("DELETE FROM `" . $this->_sPrefix . "featured_orders` WHERE `buyer_id` = $iOwner"); 

        }
        return $iRet;
    }


	//[begin] - ultimate groups mod from modzzz   

	function isValidInvite($iEntryId, $sCode=''){
  
		return (int)$this->getOne ("SELECT COUNT(`id`) FROM `" . $this->_sPrefix . "invite` WHERE `id_entry` = '$iEntryId' AND `code` = '$sCode'");
	}

	function isExistsInvite($iEntryId, $iProfileId=0){
 
		return (int)$this->getOne ("SELECT COUNT(`id`) FROM `" . $this->_sPrefix . "invite` WHERE `id_entry` = '$iEntryId' AND `id_profile` = '$iProfileId'");
	}

	function removeInvite($iEntryId, $iProfileId){
		$this->query ("DELETE FROM `" . $this->_sPrefix . "invite` WHERE `id_entry` = '$iEntryId' AND `id_profile` = '$iProfileId'");
	}

	function addInvite($iEntryId, $iProfileId=0){ 
		if(!$this->isExistsInvite($iEntryId, $iProfileId)){
			$sInviteCode = $this->_getCode();

			$this->query ("INSERT INTO `" . $this->_sPrefix . "invite` SET `code` = '$sInviteCode' ,`id_entry` = '$iEntryId', `id_profile` = '$iProfileId'");

			return $sInviteCode;
		}
	}

	function _getCode() {
		list($fMilliSec, $iSec) = explode(' ', microtime());
		$fSeed = (float)$iSec + ((float)$fMilliSec * 100000);
		srand($fSeed);

		$sResult = '';
		for($i=0; $i < 16; ++$i) {
			switch(rand(1,2)) {
				case 1: 
					$c = chr(rand(ord('A'),ord('Z')));
					break;
				case 2: 
					$c = chr(rand(ord('0'),ord('9')));
					break;
			}
			$sResult .= $c;
		}
		return $sResult;
	}
 
 	function getStateCount($sState){
		
		if (!$GLOBALS['logged']['admin']){ 
			if ($GLOBALS['logged']['member']){ 
				$aProfile = getProfileInfo($_COOKIE['memberID']); 
				require_once(BX_DIRECTORY_PATH_INC . 'membership_levels.inc.php');
				$aMembershipInfo = getMemberMembershipInfo($_COOKIE['memberID']); 
				$iMembershipId = $aMembershipInfo['ID']; 

			    $sExtraCheck = " AND `group_membership_view_filter` IN ('', '$iMembershipId')"; 
			}else{
				$sExtraCheck = "AND `group_membership_view_filter`=''";
			}
		}
 
		return  $this->getOne("SELECT COUNT(`id`) FROM `" . $this->_sPrefix . "main` WHERE  `state` = '$sState'  AND `status`='approved' {$sExtraCheck}"); 
	}

 	function getStateName($sState){
		$sState = $this->getOne("SELECT `State` FROM `States` WHERE `StateCode`='{$sState}' LIMIT 1");
		
		return $sState;
	}

	function getStateOptions($sCountry='') {
		$aStates = $this->getStateArray ($sCountry);

		foreach($aStates as $aEachCode=>$aEachState){ 
			$sOptions .= "<option value='{$aEachCode}'>{$aEachState}</option>";
		}

		return $sOptions;
	}

 	function getStateArray($sCountry=''){
 
		$aStates = array();
		$aDbStates = $this->getAll("SELECT * FROM `States` WHERE `CountryCode`='{$sCountry}'  ORDER BY `State` ");
		
		$aStates[] = '';
		foreach ($aDbStates as $aEachState){
			$sState = $aEachState['State'];
			$sStateCode = $aEachState['StateCode'];
			
			$aStates[$sStateCode] = $sState;
  		} 
		return $aStates;
	}
 
	function getCategories($sType)
	{ 
 		$aAllEntries = $this->getAll("SELECT `Category` FROM `sys_categories` WHERE `Type` = '{$sType}' AND `Status`='active' AND Owner=0"); 
		
		return $aAllEntries; 
	}

	function getCategoryCount($sType,$sCategory)
	{ 
		$sCategory = process_db_input($sCategory); 
		$iNumCategory = $this->getOne("SELECT count(`" . $this->_sPrefix . "main`.`id`) FROM `" . $this->_sPrefix . "main`  inner JOIN `sys_categories` ON `sys_categories`.`ID`=`" . $this->_sPrefix . "main`.`id` WHERE 1 AND  `sys_categories`.`Category` IN('{$sCategory}') AND `sys_categories`.`Type` = '{$sType}' AND `" . $this->_sPrefix . "main`.`status`='approved'"); 
		
		return $iNumCategory;
	}

	function flagActivity($sType, $iEntryId, $iProfileId, $aParams=array()){
 
		if(!$iEntryId)
			return;

		switch($sType){ 
			case 'mark_as_featured':
				foreach($aParams as $sKey=>$iValue){ 
					if($sKey=='Featured'){
						if($iValue)
							$sType = "unfeatured";
						else
							$sType = "featured"; 
					}
				}
			break; 
		}

		$aTypes = array(
			'add' => '_bx_groups_feed_post',
			'delete' => '_bx_groups_feed_delete',
			'change' => '_bx_groups_feed_post_change',
			'join' => '_bx_groups_feed_join',
			'unjoin' => '_bx_groups_feed_unjoin',
			'remove' => '_bx_groups_feed_remove',
			'rate' => '_bx_groups_feed_rate',
			'commentPost' => '_bx_groups_feed_comment',
			'featured' => '_bx_groups_feed_featured',
			'unfeatured' => '_bx_groups_feed_unfeatured',
			'makeAdmin' => '_bx_groups_feed_make_admin',
			'removeAdmin' => '_bx_groups_feed_remove_admin'  
		);
   
		$aDataEntry = $this->getEntryById($iEntryId);
		
		$sProfileNick = getNickName($iProfileId);
		$sProfileLink = getProfileLink($iProfileId);
		$sGroupUri = $aDataEntry['uri'];
		$sGroupTitle = process_db_input($aDataEntry['title']);
		$sGroupUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $sGroupUri;
	
		$sParams = "profile_id|{$iProfileId};profile_link|{$sProfileLink};profile_nick|{$sProfileNick};entry_url|{$sGroupUrl};entry_title|{$sGroupTitle}";

		$sLangKey = $aTypes[$sType];
 
		$this->query("INSERT INTO bx_groups_activity(`group_id`,`lang_key`,`params`,`type`) VALUES ($iEntryId,'$sLangKey','$sParams','$sType')");

	}

	function getActivityFeed($iLimit=5){

		return $this->getAll("SELECT `group_id`,`lang_key`,`params`,`type`,UNIX_TIMESTAMP(`date`) AS `date` FROM `bx_groups_activity` ORDER BY `date` DESC LIMIT $iLimit");

	}

	function getLatestComments($iLimit=5){

		return $this->getAll("SELECT `cmt_object_id`,`cmt_author_id`,`cmt_text`, UNIX_TIMESTAMP(`cmt_time`) AS `date` FROM `bx_groups_cmts` WHERE `cmt_text` NOT LIKE '<object%' ORDER BY `cmt_time` DESC LIMIT $iLimit");

	}  
	//[end] - ultimate groups mod from modzzz 


	/*[begin] map*/
    function updateLocation ($iAuthorId, $iId, $fLat, $fLng, $iZoom, $iType) {
        return $this->query ("INSERT INTO `" . $this->_sPrefix . "profiles` SET `id` = '$iId', `author_id` = '$iAuthorId', `ts` = UNIX_TIMESTAMP(), `lat` = '$fLat', `lng` = '$fLng', `zoom` = '$iZoom', `type` = '$iType' ON DUPLICATE KEY UPDATE `ts` = UNIX_TIMESTAMP(), `lat` = '$fLat', `lng` = '$fLng', `zoom` = '$iZoom', `type` = '$iType'");
    }

    function deleteLocation ($iId) {
        return $this->query ("DELETE FROM `" . $this->_sPrefix . "profiles` WHERE `id` = '$iId'");
    }

    function insertCountryLocation ($sCountryCode, $fLat, $fLng, $isFailed = 0) {
        return $this->query ("INSERT INTO `" . $this->_sPrefix . "countries` SET `country` = '$sCountryCode', `lat` = '$fLat', `lng` = '$fLng', `failed` = '$isFailed' ON DUPLICATE KEY UPDATE `lat` = '$fLat', `lng` = '$fLng', `failed` = '$isFailed'");
    }

    function insertCityLocation ($sCountryCode, $sCity, $fLat, $fLng, $isFailed = 0) {
        return $this->query ("INSERT INTO `" . $this->_sPrefix . "cities` SET `country` = '$sCountryCode', `city` = '$sCity', `lat` = '$fLat', `lng` = '$fLng', `failed` = '$isFailed' ON DUPLICATE KEY UPDATE `lat` = '$fLat', `lng` = '$fLng', `failed` = '$isFailed'");
    }

    function insertProfileLocation ($iAuthorId, $iId, $fLat, $fLng, $iMapZoom, $sMapType, $sAddress, $sCountry, $iPrivacy = 0, $isFailed = 0) {
        $sPrivacyUpdate = '';
        $sPrivacyInsert = "`allow_view_location_to` = '" . BX_GROUPS_DEFAULT_PRIVACY . "',";
        if ($iPrivacy) {
            $sPrivacyInsert = $sPrivacyUpdate = "`allow_view_location_to` = '$iPrivacy',";
        }
        return $this->query ("INSERT INTO `" . $this->_sPrefix . "profiles` SET `id` = '$iId', `author_id` = '$iAuthorId', `lat` = '$fLat', `lng` = '$fLng', `zoom` = '$iMapZoom', `type` = '$sMapType', `address` = '$sAddress', `country`= '$sCountry', $sPrivacyInsert `ts` = UNIX_TIMESTAMP(), `failed` = '$isFailed' ON DUPLICATE KEY UPDATE  `lat` = '$fLat', `lng` = '$fLng', `zoom` = '$iMapZoom', `type` = '$sMapType', `address` = '$sAddress', `country`= '$sCountry', $sPrivacyUpdate `ts` = UNIX_TIMESTAMP(), `failed` = '$isFailed'");
    }

    function getUndefinedCountries ($iLimit) {
        return $this->getPairs ("SELECT `c`.`ISO2`, `c`.`country` FROM `sys_countries` AS `c` LEFT JOIN `" . $this->_sPrefix . "countries` AS `m` ON (`m`.`country` = `c`.`ISO2`) WHERE ISNULL(`m`.`country`) LIMIT $iLimit", 'ISO2', 'country');
    }

    function getUndefinedCities ($iLimit) {
        return $this->getPairs ("SELECT `p`.`city`, `p`.`country` FROM `" . $this->_sPrefix . "main` AS `p` LEFT JOIN `" . $this->_sPrefix . "cities` AS `m` ON (`m`.`country` = `p`.`country` AND `m`.`city` = `p`.`city`) WHERE ISNULL(`m`.`country`) LIMIT $iLimit", 'country', 'city');
    }    

    function getUndefinedProfiles ($iLimit) {
        return $this->getAllWithKey ("SELECT `p`.* FROM `" . $this->_sPrefix . "main` AS `p` LEFT JOIN `" . $this->_sPrefix . "profiles` AS `m` ON (`m`.`id` = `p`.`id`) WHERE ISNULL(`m`.`id`) LIMIT $iLimit", 'id');
    }    

    function getProfileInfo ($iID) {
        return $this->getRow("SELECT `id`, `uri`, `title`, `thumb`, `country`, `city`, `zip`, `author_id` FROM `" . $this->_sPrefix . "main` WHERE `id`='$iID'");
    }    
 
    function clearProfiles ($isClearFailedOnly) {
        return $this->_clearTable ($isClearFailedOnly, 'profiles');
    }

    function clearCountries ($isClearFailedOnly) {
        return $this->_clearTable ($isClearFailedOnly, 'countries');
    }

    function clearCities ($isClearFailedOnly) {
        return $this->_clearTable ($isClearFailedOnly, 'cities');
    }

    function _clearTable ($isClearFailedOnly, $sTable) {
        if ($isClearFailedOnly) {
            $ret = $this->query ("DELETE FROM `" . $this->_sPrefix . "$sTable` WHERE `failed` != 0");
            $this->query ("OPTIMIZE TABLE `" . $this->_sPrefix . "$sTable`");
            return $ret;
        } else {
            return $this->query ("TRUNCATE TABLE `" . $this->_sPrefix . "$sTable`");
        }
    }    

    function getProfileById($iProfileId) { 
        return $this->getRow("SELECT `m`.`id`, `p`.`title`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, `m`.`zoom`, `m`.`type`, `m`.`address`, `m`.`country`, `p`.`city`, `m`.`allow_view_location_to` FROM `" . $this->_sPrefix . "profiles` AS `m` INNER JOIN `" . $this->_sPrefix . "main` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`failed` = 0 AND `p`.`status` = 'approved' AND `m`.`id` = '$iProfileId' LIMIT 1");
    } 

    function getAuthorById($iProfileId) { 
        return $this->getRow("SELECT `author_id` FROM `" . $this->_sPrefix . "main` WHERE `id` = '$iProfileId' LIMIT 1");
    } 


    function getProfilesByBounds($fLatMin, $fLatMax, $fLngMin, $fLngMax) {
        $sWhere = $this->_getLatLngWhere ($fLatMin, $fLatMax, $fLngMin, $fLngMax);
        return $this->getAll("SELECT `m`.`id`, `p`.`thumb`, `p`.`title` AS `NickName`, `m`.`lat`, `m`.`lng` FROM `" . $this->_sPrefix . "profiles` AS `m` INNER JOIN `" . $this->_sPrefix . "main` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`failed` = 0 AND `p`.`status` = 'approved' AND `m`.`allow_view_location_to` = '" . BX_DOL_PG_ALL . "' $sWhere LIMIT 100");
    } 

    function getCountryByCode($sCountryCode, $isScrict = true) {

        $sJoin = $isScrict ? 'INNER' : 'LEFT';

        return $this->getRow("SELECT `m`.`country`, `m`.`lat`, `m`.`lng`, COUNT(`p`.`id`) AS `num`
            FROM `" . $this->_sPrefix . "countries` AS `m` 
            $sJoin JOIN `" . $this->_sPrefix . "main` AS `p` ON (`p`.`country` = `m`.`country` AND `p`.`status` = 'approved') 
            $sJoin JOIN `" . $this->_sPrefix . "profiles` AS `pm` ON (`pm`.`id` = `p`.`id` AND `pm`.`failed` = 0 AND `pm`.`allow_view_location_to` = '" . BX_DOL_PG_ALL . "')
            WHERE `m`.`failed` = 0 AND `m`.`country` = '$sCountryCode'
            GROUP BY `p`.`country`
            LIMIT 1"); 
    } 

    function getCountriesByBounds($fLatMin, $fLatMax, $fLngMin, $fLngMax) {
        $sWhere = $this->_getLatLngWhere ($fLatMin, $fLatMax, $fLngMin, $fLngMax);
        return $this->getAll("SELECT `m`.`country`, `m`.`lat`, `m`.`lng`, COUNT(`p`.`id`) AS `num`
            FROM `" . $this->_sPrefix . "countries` AS `m` 
            INNER JOIN `" . $this->_sPrefix . "main` AS `p` ON (`p`.`country` = `m`.`country` AND `p`.`status` = 'approved') 
            INNER JOIN `" . $this->_sPrefix . "profiles` AS `pm` ON (`pm`.`id` = `p`.`id` AND `pm`.`failed` = 0 AND `pm`.`allow_view_location_to` = '" . BX_DOL_PG_ALL . "')
            WHERE `m`.`failed` = 0 $sWhere 
            GROUP BY `p`.`country`
            LIMIT 100"); 
    } 

    function getCitiesByBounds($fLatMin, $fLatMax, $fLngMin, $fLngMax) {
        $sWhere = $this->_getLatLngWhere ($fLatMin, $fLatMax, $fLngMin, $fLngMax);
        return $this->getAll("SELECT `m`.`country`, `m`.`city`, `m`.`lat`, `m`.`lng`, COUNT(`p`.`id`) AS `num`
            FROM `" . $this->_sPrefix . "cities` AS `m`
            INNER JOIN `" . $this->_sPrefix . "main` AS `p` ON (`p`.`country` = `m`.`country` AND `p`.`city` = `m`.`city` AND `p`.`status` = 'approved')
            INNER JOIN `" . $this->_sPrefix . "profiles` AS `pm` ON (`pm`.`id` = `p`.`id` AND `pm`.`failed` = 0 AND `pm`.`allow_view_location_to` = '" . BX_DOL_PG_ALL . "')
            WHERE `m`.`failed` = 0 $sWhere 
            GROUP BY `m`.`city`
            LIMIT 100"); 
    } 

    function _getLatLngWhere ($fLatMin, $fLatMax, $fLngMin, $fLngMax) {

        $sWhere = " AND `m`.`lat` < $fLatMax AND `m`.`lat` > $fLatMin ";
        if ($fLngMin < $fLngMax)
            $sWhere .= " AND `m`.`lng` < $fLngMax AND `m`.`lng` > $fLngMin ";
        else
            $sWhere .= " AND ((`m`.`lng` < $fLngMax AND `m`.`lng` > -180) OR (`m`.`lng` < 180 AND `m`.`lng` > $fLngMin)) ";
        return $sWhere;
    }    

    function isCityLocationExists($sCountryCode, $sCity) {
        return $this->getOne("SELECT `m`.`country` FROM `" . $this->_sPrefix . "cities` AS `m` WHERE `m`.`country` = '$sCountryCode' AND `m`.`city` = '$sCity' AND `m`.`failed` = 0 LIMIT 1") ? true : false;
    }

    function getSettingsCategory($s) {
        return $this->getOne("SELECT `ID` FROM `sys_options_cats` WHERE `name` = '$s' LIMIT 1");
    }    
	/*[end] map*/


	/***** SPONSOR **************************************/
    function getSponsorEntryById($iId) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableSponsor . "` WHERE `id` = $iId LIMIT 1");
    }
 
    function getSponsorEntryByUri($sUri) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableSponsor . "` WHERE `uri` = '$sUri' LIMIT 1");
    }
 
    function deleteSponsorByIdAndOwner ($iId, $iGroupId,  $iOwner, $isAdmin) {
        $sWhere = '';
        if (!$isAdmin) 
            $sWhere = " AND `author_id` = '$iOwner' ";
        if (!($iRet = $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableSponsor . "` WHERE `id` = $iId AND `group_id`=$iGroupId $sWhere LIMIT 1")))
            return false;
        $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableSponsorMediaPrefix . "images` WHERE `entry_id` = $iId");
  
        return true;
    } 
	
	/***** VENUE **************************************/
    function getVenueEntryById($iId) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableVenue . "` WHERE `id` = $iId LIMIT 1");
    }
 
    function getVenueEntryByUri($sUri) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableVenue . "` WHERE `uri` = '$sUri' LIMIT 1");
    }
 
    function deleteVenueByIdAndOwner ($iId, $iGroupId,  $iOwner, $isAdmin) {
        $sWhere = '';
        if (!$isAdmin) 
            $sWhere = " AND `author_id` = '$iOwner' ";
        if (!($iRet = $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableVenue . "` WHERE `id` = $iId AND `group_id`=$iGroupId $sWhere LIMIT 1")))
            return false;
        $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableVenueMediaPrefix . "images` WHERE `entry_id` = $iId");
  
        return true;
    } 
 
	/***** NEWS **************************************/
    function getNewsEntryById($iId) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableNews . "` WHERE `id` = $iId LIMIT 1");
    }
 
    function getNewsEntryByUri($sUri) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableNews . "` WHERE `uri` = '$sUri' LIMIT 1");
    }
 
    function deleteNewsByIdAndOwner ($iId, $iGroupId,  $iOwner, $isAdmin) {
        $sWhere = '';
        if (!$isAdmin) 
            $sWhere = " AND `author_id` = '$iOwner' ";
        if (!($iRet = $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableNews . "` WHERE `id` = $iId AND `group_id`=$iGroupId $sWhere LIMIT 1")))
            return false;
        $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableNewsMediaPrefix . "images` WHERE `entry_id` = $iId");
  
        return true;
    } 


	/***** EVENT **************************************/
    function getEventEntryById($iId) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableEvent . "` WHERE `id` = $iId LIMIT 1");
    }
 
    function getEventEntryByUri($sUri) {
         return $this->getRow ("SELECT * FROM `" . $this->_sPrefix . $this->_sTableEvent . "` WHERE `uri` = '$sUri' LIMIT 1");
    }
 
    function deleteEventByIdAndOwner ($iId, $iGroupId,  $iOwner, $isAdmin) {
        $sWhere = '';
        if (!$isAdmin) 
            $sWhere = " AND `author_id` = '$iOwner' ";
        if (!($iRet = $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableEvent . "` WHERE `id` = $iId AND `group_id`=$iGroupId $sWhere LIMIT 1")))
            return false;
        $this->query ("DELETE FROM `" . $this->_sPrefix . $this->_sTableEventMediaPrefix . "images` WHERE `entry_id` = $iId");
  
        return true;
    } 


	//BEGIN RSS 
	function getRss($iEntryId, $iLimit=0){

		if($iLimit)
			$sQuery = "LIMIT 0, {$iLimit}";

		return $this->getAll("SELECT `id`, `id_entry`, `url`, `name` FROM `" . $this->_sPrefix . "rss` WHERE `id_entry`={$iEntryId} {$sQuery}");
	}

 	function addRss($iEntryId){

		foreach($_POST['rsscaption'] as $iKey=>$sValue){
		
			$sRssName = process_db_input($sValue);
 			$sRssLink = process_db_input($_POST['rsslink'][$iKey]);
 
			if(trim($sRssName)){  
				$this->query("INSERT INTO `" . $this->_sPrefix . "rss` SET `id_entry`=$iEntryId, `url`='$sRssLink', `name`='$sRssName'");
			}
		} 
	}

	function removeEntryRss($iEntryId){ 
	   
		$this->query("DELETE FROM `" . $this->_sPrefix . "rss` WHERE `id_entry`='$iEntryId'");   
	}

	function removeRss($iEntryId, $iFeedId){ 
	   
		$this->query("DELETE FROM `" . $this->_sPrefix . "rss` WHERE `id_entry`='$iEntryId' AND `id`='$iFeedId'");   
	}

    function getRssIds ($iEntryId) {
		return $this->getPairs ("SELECT `id` FROM `" . $this->_sPrefix . "rss`  WHERE `id_entry` = '$iEntryId'", 'id', 'id');
    }
	//END RSS



	/*featured functions*/ 
    function getCurrencySign($sKey){ 
		
		$sKey = ($sKey) ? $sKey : $this->_oConfig->_sCurrencySign;
		
		return $sKey;  
    }

	function setItemStatus($iItemId, $sStatus) {
		
 		 $this->query("UPDATE `" . $this->_sPrefix . "main` SET `status`='$sStatus' WHERE `id`='$iItemId'"); 
	}
 
   
   function generateFeaturedPaymentUrl($iGroupId, $iQuantity, $fCost) {
        $fCost   = number_format($fCost, 2);
 
        return  $this ->_oConfig->getPurchaseBaseUrl() . '?cmd=_xclick'
			    . '&rm=2'
                . '&no_shipping=0'      
				. '&currency_code='.$this->_oConfig->getPurchaseCurrency()
                . '&return=' .  $this->_oConfig->getFeaturedCallbackUrl() . $iGroupId
				. '&business='  . getParam('bx_groups_paypal_email')
                . '&item_name=' . getParam('bx_groups_featured_purchase_desc')
                . '&item_number=' . $iGroupId  
                . '&amount=' . $fCost;
    }
 
    function saveFeaturedTransactionRecord($iBuyerId, $iGroupId, $iQuantity, $fPrice, $sTransId, $sTransType) {
        $iBuyerId    = (int)$iBuyerId;
        $iGroupId  = (int)$iGroupId; 
        $iQuantity  = (int)$iQuantity; 
		$iTime = time();

        $bProcessed = $this->query("INSERT INTO `" . $this->_sPrefix . "featured_orders` 
							SET `buyer_id` = {$iBuyerId}, 
							`price` = '{$fPrice}',
							`days` = {$iQuantity},
							`item_id` =  {$iGroupId},
 							`trans_id` = '{$sTransId}',  
							`trans_type` = '{$sTransType}', 
  							`created` = $iTime  
        "); 

 		$iOrderId = $this->lastId();

		if($iOrderId){
			$this->alertOnAction('bx_groups_featured_admin_notify', $iGroupId, $iBuyerId, $iQuantity, true);

			$this->alertOnAction('bx_groups_featured_buyer_notify', $iGroupId, $iBuyerId, $iQuantity);
		}

		return $iOrderId; 
    }

    function updateFeaturedEntryExpiration($iEntryId, $iDays) { 

		 $SECONDS_IN_DAY = 86400; 
		 $iCreated = time();
 
		 $aDataEntry = $this->getEntryById($iEntryId);
		 $iExistExpireDate = $aDataEntry['featured_expiry_date'];
		
		 if($iExistExpireDate < $iCreated){ 
		     $iExpireDate = $iCreated + ($SECONDS_IN_DAY * $iDays);

			 $bProcessed = $this->query("UPDATE `" . $this->_sPrefix . "main` SET `featured`=1, `featured_expiry_date` = $iExpireDate, `featured_date`=$iCreated WHERE `id` = '{$iEntryId}'"); 
		 }else{
		     $iExpireDate = ($SECONDS_IN_DAY * $iDays);

			 $bProcessed = $this->query("UPDATE `" . $this->_sPrefix . "main` SET `featured`=1, `featured_expiry_date` = `featured_expiry_date` + $iExpireDate, `featured_date`=$iCreated  WHERE `id` = '{$iEntryId}'"); 
		 }
	
		 return $bProcessed;
	}


    function isExistFeaturedTransaction($iBuyerId, $sTransID) {
        $iBuyerId  = (int)$iBuyerId;
 
        return $this->getOne("SELECT COUNT(`trans_id`) FROM `" . $this->_sPrefix . "featured_orders` 
            WHERE `buyer_id` = {$iBuyerId} AND `trans_id` =  '{$sTransID}'  
        "); 
    }

	function processGroups(){ 
  
		$this->processFeaturedGroups();
	}
 
	function processFeaturedGroups(){
		
		if(getParam('bx_groups_buy_featured') != 'on')
			return;

		$iTime = time();
   
        $aGroups = $this->getAll("SELECT `id`, `author_id`, `featured`, `featured_expiry_date` FROM `" . $this->_sPrefix . "main` WHERE `featured`=1 AND `featured_expiry_date` <= $iTime"); 

		foreach($aGroups as $aEachList){

		    $iExistExpireDate = (int)$aEachList['featured_expiry_date']; 
		    if($iExistExpireDate==0)
				continue;

			$iGroupId = (int)$aEachList['id'];
			$iRecipientId = (int)$aEachList['author_id'];

			$this->alertOnAction('bx_groups_featured_expire_notify', $iGroupId, $iRecipientId  );
		
	        $this->query("UPDATE `" . $this->_sPrefix . "main` SET `featured`=0, `featured_expiry_date`=0, `featured_date`=0  WHERE `id`=$iGroupId"); 
		}

	}

	function alertOnAction($sTemplate, $iGroupId, $iRecipientId=0, $iDays=0, $bAdmin=false) {
	   
		$aPlus = array();

		if($iGroupId){
			$aDataEntry = $this->getEntryById($iGroupId);
			$aPlus['ListTitle'] = $aDataEntry['title']; 
			$aPlus['ListLink'] = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri']; 
		}

		if($iRecipientId){
			$aRecipient = getProfileInfo($iRecipientId); 
			$aPlus['NickName'] = $aRecipient['NickName']; 
			$aPlus['NickLink'] = getProfileLink($iRecipientId);
			$sNotifyEmail = $aRecipient['Email']; 
		}

		$aPlus['Days'] = $iDays; 
		$aPlus['SiteName'] = isset($GLOBALS['site']['title']) ? $GLOBALS['site']['title'] : getParam('site_title');
		$aPlus['SiteUrl'] = isset($GLOBALS['site']['url']) ;
 
		$oEmailTemplate = new BxDolEmailTemplates(); 

		$aTemplate = $oEmailTemplate->getTemplate($sTemplate, $iRecipientId);
		$sMessage = $aTemplate['Body'];
		$sSubject = $aTemplate['Subject'];   
		$sSubject = str_replace("<SiteName>", $aPlus['SiteName'], $sSubject);

		if($bAdmin){
			$sNotifyEmail = $GLOBALS['site']['email_notify'];
			$iRecipientId = 0;
		}
 
		sendMail($sNotifyEmail, $sSubject, $sMessage, $iRecipientId, $aPlus, 'html' );   
	}





}

?>